package com.nulldev.util.languages.json.uniapi;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.JVM.Arguments.ArgumentInit;
import com.nulldev.util.JVM.JVM;
import com.nulldev.util.VariableAPI.RandomUtil;

public class UniJsonIterableValue extends UniJsonValue implements Iterable<UniJsonValue> {

	public UniJsonIterableValue(Object o) {
		super(o);
	}

	public UniJsonIterableValue(final UniJsonValue o) {
		super(o.o);
		if (!o.isArray())
			throw new UnsupportedOperationException("o is not an array!");
	}

	@Override
	public Iterator<UniJsonValue> iterator() {
		return this.get_array().raw_array();
	}

	@Override
	public void forEach(Consumer<? super UniJsonValue> action) {
		this.get_array().raw_array().forEachRemaining(action);
	}

	@Override
	public Spliterator<UniJsonValue> spliterator() {
		final Iterator<UniJsonValue> v = this.get_array().raw_array();
		return Spliterators.spliterator(v, this.size(), 0);
	}

	public static void main(String[] args) {
		Arguments.argumentInit(new ArgumentInit() {

			@Override
			public void onInit(Arguments args) {
				args.addArgument(JSONAPI.ARGUMENT);
			}
		});
		Arguments.setup(args);
		final int am = RandomUtil.randInt(10, 60);
		final UniJsonValue uni = UniJsonValue.array(am);
		uni.print_providers();
		for (int i = 0; i < am; i++) {
			uni.add(RandomUtil.hexString(64));
		}
		uni.debug_array_print();
		uni.asArray().forEach((c) -> {
			JVM.println(c);
		});
		uni.asArray().spliterator().forEachRemaining((e) -> {
			JVM.println("- " + e);
		});
	}

	public UniJsonValue getIfInList(final int i) {
		if (i > -1 && i < this.length())
			return this.get(i);
		return null;
	}

//	JDK 18: Compat: Remove ALL finalize instances.
//	@Override
//	public void finalize() throws Throwable {
//		super.finalize();
//	}

	public UniJsonValue random() {
		final int size = super.size();
		if (size == 0)
			return null;
		return this.get(RandomUtil.randInt(0, size));
	}

	public void copy(final String[] data) {
		if (data == null)
			throw new NullPointerException("tags == null!");
		if (data.length == 0)
			return;
		for (final String entry : data) {
			super.add(entry);
		}
	}

}
